package com.example.question.tree.tree1;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @Date 2023-07-09
 * @Author Jonathan
 */
public class Code13_199 {
    public static void main(String[] args) {
        TreeNode treeNode = Tree.createTree(new Integer[]{1, 2, 4, null, null, null, 3, null, null});
        Code13_199 code = new Code13_199();
        System.out.println(code.rightSideView(treeNode));
    }


    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if (root == null) return ret;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            int rightMost = Integer.MIN_VALUE;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                // 更新最右边的值
                rightMost = node.val;
                if (node.left != null) {
                    queue.offer(node.left);
                }

                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            // 将最右边的值放到放回结果里面
            ret.add(rightMost);
        }
        return ret;
    }
}
